<?php

namespace app\controllers\h5\execute;

use app\commission\Commission;
use app\controllers\h5\base\H5Controller;
use app\models\marketing\MarketingBasic;
use app\models\system\SetApp;
use app\models\system\SetBasic;
use app\models\system\SetQrcode;
use app\models\system\SetWx;
use app\models\user\User;
use app\models\user\UserBank;
use app\models\user\UserPayPassword;
use app\models\user\UserSignIn;
use app\redis\Cache;
use app\util\Agent;
use app\util\Qrcode;
use app\util\Util;
use Firebase\JWT\JWT;
use Yii;

/**
 * Class UserController
 * @package app\controllers\h5\execute
 */
class UserController extends H5Controller
{
    /**
     * jwt auth
     *
     * @param $authorization
     * @param $key
     * @return bool
     */
    private function jwtAuthentication($authorization, $key)
    {
        try {
            // 时间
            JWT::$leeway = 60;
            $decode = JWT::decode($authorization, $key, ['HS256']);
            // var_dump($decode);exit;
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * check login by token
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionIsLogin()
    {
        $token = $this->post('token');
        $key = Yii::$app->params['JWT_H5_KEY'];

        // $code = Yii::$app->params['CODE_SUCCESS'];

        if ($this->jwtAuthentication($token, $key)) {
            return $this->successEncode(['isLogin' => true], '正常状态');
        }

        return $this->successEncode(['isLogin' => false], '登录过期');
    }

    /**
     * referrer qrcode list 
     * 
     * @return array|string[]|\yii\web\Response
     */
    public function actionQrcode()
    {
        $u = User::findOne(['id' => $this->user->id]);
        if ($u->level < 1) {
            return $this->fail('会员才有推荐码');
        }

        $code = $this->post('code');

        $id = $this->user->id;
        $key = Cache::$USER_QRCODE . $id;



        $cache = Cache::get($key);
        if ($cache && false) {
            $data = json_decode($cache, true);

            $result = [
                'qrcode' => $data['qrcode'],
                'list' => $data['list'],
                'text' => $data['text']
            ];

            return $this->successEncode($result);
        }

        $set = SetApp::getLastOne();
        $string = $set->domain . $code . $id;
        $name = '/qrcode/referrer/' . $id . '.png';

        // var_dump($u->avatar);exit;
        $ax = '';
        if ($u->avatar && strlen($u->avatar) > 10) {
            $base = Yii::$app->getBasePath() . '/web';
            $ax = '/qrcode/referrer/avatar-' . $id . '.png';
            $avatar = $base . $ax;
            $dir = dirname($avatar);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
                chmod($dir, 0777);
            }
            if (!is_file($avatar)) {
                $s = @file_get_contents($u->avatar);
                @file_put_contents($avatar, $s);
                \yii\imagine\Image::thumbnail($avatar, 50, 50)
                    ->save($avatar, ['quality' => 100]);
            }
        }

        $list = [];
        $base = '';
        // if (!Qrcode::isExist($name)) {
        //
        //     Qrcode::generate($string, $name, 180);
        //     $base = $name;
        //
        //     // list
        //     $qrcode = SetQrcode::getLastOne();
        //     if ($qrcode['images'] && count($qrcode['images']) > 0) {
        //         foreach ($qrcode['images'] as $item) {
        //             $poster = $item['path'];
        //             $real = '/qrcode/referrer/' . $id . '-' . $item['id'] . '.png';
        //             Qrcode::setPoster($name, $poster, $real, [93, 320]);
        //             array_push($list, $set->domain . $real);
        //         }
        //     }
        // }

        Qrcode::generate($string, $name, 120);
        $base = $name;

        // list
        $qrcode = SetQrcode::getLastOne();
        if ($qrcode['images'] && count($qrcode['images']) > 0) {
            foreach ($qrcode['images'] as $item) {

                // poster
                $poster = $item['path'];
                $real = '/qrcode/referrer/' . $id . '-' . $item['id'] . '.png';
                Qrcode::setPoster($name, $poster, $real, [123, 280]);

                // avatar
                if ($ax) {
                    Qrcode::setPoster($ax, $real, $real, [30, 480]);
                }

                // text
                // Qrcode::setText($real, '推荐人ID: ' . $id, '', [120, 498], '16', '#000000');
                Qrcode::setText($real, base64_decode($u->nickname), '', [160, 498], '16', '#000000');




                array_push($list, $set->domain . $real);
            }
        }

        $data = [
            'qrcode' => $set->domain . $base,
            'list' => $list,
            'text' => $string
        ];

        Cache::set($key, json_encode($data));

        return $this->successEncode($data);
    }

    /**
     * wx subscribe qrcode
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionSubscribe()
    {
        $key = Cache::$SUBSCRIBE;
        $cache = Cache::get($key);

        if (!$cache) {
            $set = SetWx::getLastOne();
            if ($set['image']) {
                $data = $set['image']['path'];
            } else {
                $data = '';
            }
            Cache::set($key, json_encode(['path' => $data]));
        } else {
            $data = json_decode($cache, true);
        }

        return $this->successEncode($data);
    }

    /**
     * user service
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionService()
    {
        $key = Cache::$USER_SERVICE;
        $cache = Cache::get($key);

        if (!$cache) {
            $set = SetBasic::getLastOne();
            $data = [
                'mobile' => $set->service_mobile,
                'wx' => $set->service_wx
            ];
            Cache::set($key, json_encode($data));
        } else {
            $data = json_decode($cache, true);
        }

        return $this->successEncode($data);
    }

    /**
     * user about
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionAbout()
    {
        $key = Cache::$USER_ABOUT;
        $cache = Cache::get($key);

        if (!$cache) {
            $set = SetBasic::getLastOne();
            $data = [
                'about' => $set->about,
            ];
            Cache::set($key, json_encode($data));
        } else {
            $data = json_decode($cache, true);
        }

        return $this->successEncode($data);
    }

    /**
     * check pay password
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCheckPayPassword()
    {
        $model = UserPayPassword::findOne(['user_id' => $this->user->id]);
        if ($model) {
            return $this->successEncode(['result' => true]);
        }

        return $this->successEncode(['result' => false]);
    }

    /**
     * edit pay password
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionEditPayPassword()
    {
        $old_password = trim($this->post('old_password'));
        $password1 = trim($this->post('password1'));
        $password2 = trim($this->post('password2'));

        if ($password2 != $password1) {
            return $this->fail('两次密码不统一');
        }

        $model = UserPayPassword::findOne(['user_id' => $this->user->id]);
        if ($model) {
            if ($model->password != $old_password) {
                return $this->fail('旧密码错误');
            }
        } else {
            $model = new UserPayPassword();
            $model->user_id = $this->user->id;
        }

        $model->password = $password1;
        if ($model->save()) {
            return $this->success();
        }

        return $this->fail('操作错误');
    }

    public function actionResetPayPassword()
    {
        $password1 = trim($this->post('password1'));
        $password2 = trim($this->post('password2'));

        if ($password2 != $password1) {
            return $this->fail('两次密码不统一');
        }

        $model = UserPayPassword::findOne(['user_id' => $this->user->id]);
        if ($model) {
            $model->password = $password1;
            if ($model->save()) {
                return $this->success();
            }
        }

        return $this->fail('操作错误');
    }

    /**
     * fetch user cash bank
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionFetchBank()
    {
        $id = $this->user->id;

        $model = UserBank::find()
            ->where(['user_id' => $id])
            ->asArray()
            ->one();

        return $this->successEncode(['bank' => $model]);
    }

    /**
     * edit user cash bank
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionEditBank()
    {
        $data = $this->post();

        $id = $this->user->id;
        $model = UserBank::findOne(['user_id' => $id]);
        if (!$model) {
            $model = new UserBank();
            $model->user_id = $id;
        }

        $model->bank_name = $data['bank_name'];
        $model->nickname = $data['nickname'];
        $model->bank_number = $data['bank_number'];
        $model->mobile = $data['mobile'];
        $model->bank_x = $data['bank_x'];

        if ($model->save()) {
            return $this->success();
        }

        return $this->fail('操作失败');
    }

    // check sign in for day
    protected function checkSignIn()
    {
        $id = $this->user->id;

        $count = UserSignIn::find()
            ->where(['user_id' => $id])
            ->andWhere(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->count();

        if ($count > 0) {
            return true;
        }

        return false;
    }

    /**
     * check user sign in for day
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCheckSignInForDay()
    {
        if ($this->checkSignIn()) {
            return $this->successEncode(['result' => true]);
        }

        return $this->successEncode(['result' => false]);
    }

    /**
     * user sign in
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionSignIn()
    {
        if ($this->checkSignIn()) {
            return $this->fail('今天已经签到过了!');
        }

        $is_wx = $this->post('is_wx');

        $transaction = Yii::$app->db->beginTransaction();

        try {

            $score = MarketingBasic::getLastOne();

            // log
            $model = new UserSignIn();
            $model->user_id = $this->user->id;
            $model->ip = Util::getClientIp();
            $model->os = Agent::getOS();
            $model->browser = Agent::getBrowse();
            $model->mobile = Agent::getMobile();
            $model->is_wx = $is_wx;
            $model->score = $score->sign_in_score;
            $model->save();

            Commission::getInstance()->getSignIn()->run($model, $score->sign_in_score);

            $transaction->commit();
            return $this->success();

        } catch (\Exception $e) {
            $transaction->rollBack();
            // return $this->fail($e->getMessage());
            return $this->fail();
        }
    }

    /**
     * user sign list
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionSignInList()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = UserSignIn::find()
            ->where(['user_id' => $this->user->id]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }
}